package com.link.auth.base.user.service;


import com.link.auth.base.user.dao.mybatis.mapper.UserMapper;
import com.link.auth.base.user.model.Role;
import com.link.auth.base.user.model.User;
import com.link.auth.core.interceptors.MyInterceptor;
import org.springframework.core.env.Environment;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class UserServiceDetail implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private Environment env;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User userQuery = new User();
        userQuery.setUserName(username);
        User user = null;
        try {
            if ("Y".equals(MyInterceptor.getThirdLoginFlag().get())
                    && "mp".equals(MyInterceptor.getThirdType().get())
                    && !StringUtils.isEmpty(MyInterceptor.getOpenId())) {
                //微信小程序去查询客户表，而不是用户表
                userQuery.setUserName(MyInterceptor.getOpenId().get());
                userQuery.setCorpId(MyInterceptor.getCorpId().get());
                user = userMapper.queryMpByUserName(userQuery);
            } else {
                user = userMapper.queryByUserName(userQuery);
            }

            if (user == null) {
                throw new UsernameNotFoundException("用户名或密码错误！");
            }
            List<Role> rolelist = new ArrayList<>();
            Role role = new Role();
            role.setName("ROLE_USER");
            rolelist.add(role);
            user.setAuthorities(rolelist);
            user.setTokenExpire(Integer.parseInt(env.getProperty("security.oauth2.client.refresh-token-validity-seconds")));
        } catch (Exception e) {
            throw new UsernameNotFoundException(e.getMessage());
        }
        return user;
    }
}
